from flask import Flask
from flask import request, session, render_template
import json

from control import handle_apply, handle_query, handle_query_detail
from control import handle_admin_login, handle_admin_list, handle_admin_inspect, handle_admin_history
import config

app = Flask(__name__)
app.secret_key = config.SECRET_KEY


@app.route('/')
@app.route('/index/')
def index():
    return render_template('index.html')


@app.route('/admin/')
def admin():
    return render_template('admin.html')


@app.route('/apply/', methods=['GET', 'POST'])
def apply():
    session.clear()
    if request.method == 'GET':
        return render_template('apply.html')
    elif request.method == 'POST':
        response = handle_apply(request.form)
        return json.dumps(response)


@app.route('/query/', methods=['GET', 'POST'])
def query():
    if request.method == 'GET':
        return render_template('query.html')
    elif request.method == 'POST':
        response = handle_query(request.form)
        if response['result'] == 'ok':
            session['auth'] = 'stu'
            session['uid'] = response['uid']
            del response['uid']
        return json.dumps(response)


@app.route('/query/<query_id>/detail/')
def query_detail(query_id):
    response = handle_query_detail({'query_id': query_id}, session=session)
    return json.dumps(response)


@app.route('/admin/login/', methods=['POST'])
def admin_login():
    response = handle_admin_login(request.form)
    if response['result'] == 'ok':
        session['auth'] = 'admin'
    return json.dumps(response)


@app.route('/admin/list/')
def admin_list():
    response = handle_admin_list({}, session=session)
    return json.dumps(response)


@app.route('/admin/inspect/', methods=['POST'])
def admin_inspect():
    response = handle_admin_inspect(request.form, session=session)
    return json.dumps(response)


@app.route('/admin/history/', methods=['GET','POST'])
def admin_history():
    if request.method == 'POST':
        response = handle_admin_history(request.form, session=session)
    elif request.method == 'GET':
        response = handle_admin_history(request.args, session=session)
    return json.dumps(response)
